<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax跨域</title>
    <script src="./res/jquery-3.5.1.min.js"></script>
</head>

<body>
    <input type="text" name="mobile" id="mobile" value="" placeholder="请输入手机号" autocomplete="off"><br>
    <input type="password" name="pwd" id="pwd" value="" placeholder="请输入密码" autocomplete="off"><br>
    <button id="login_btn">登录</button>
</body>

</html>
<script>
    window.addEventListener('DOMContentLoaded', function(e) {
        // 获取后端服务器地址
        $.getJSON("./res/server.json",
            function(data, textStatus, jqXHR) {
                let url = data.protocol + data.domain + data.port + data.context;
                sessionStorage.setItem('server', url);
            }
        ), false;
        let login_btn = window.document.querySelector('#login_btn');
        let form = window.document.querySelectorAll('input');

        login_btn.addEventListener('click', function(e) {
            let data = {};
            for (let index = 0; index < form.length; index++) {
                const element = form[index];
                data[element.name] = element.value;
            }
            $.ajax({
                type: "post",
                url: sessionStorage.getItem('server') + 'rest/user/login',
                data: JSON.stringify(data),
                contentType: "application/json;charset=UTF-8",
                // 允许ajax跨域携带cookie
                xhrFields: {
                    withCredentials: true
                },
                // 允许ajax跨域
                crossDomain: true,
                dataType: "json",
                success: function(response) {
                    window.console.log(response);
                }
            });
        });


    });
</script>